#ifndef THREAD_TEST_H
#define THREAD_TEST_H

#include <iostream>

#include <thread>
#include <mutex>
#include <condition_variable>

#include <atomic> // 原子操作

#include <chrono>//C++时间处理工具


#include <vector>
#include <string>

#include <memory> //std::shared_ptr    std::unique_ptr

#include <Windows.h> //Sleep


class noncopyable
{
 public:
  noncopyable(const noncopyable&) = delete;
  void operator=(const noncopyable&) = delete;

 protected:
  noncopyable() = default;
  ~noncopyable() = default;
};


class ThreadGuard : public noncopyable
{
    std::thread& t;
public:
    explicit ThreadGuard(std::thread& t_):
        t(t_)
    {}
    ~ThreadGuard()
    {
        std::cout << "ThreadGuard destructor" << std::endl;
        if(t.joinable())
        {
            std::cout << "thread can join" << std::endl;
            t.join();
        }
    }
//    thread_guard(thread_guard const&)=delete;
//    thread_guard& operator=(thread_guard const&)=delete;
};


class Thread_test : public noncopyable
{
public:
    explicit Thread_test();
    ~Thread_test()
    {
        std::cout << "Thread_test destructor" << std::endl;

        m_bNeedRun = false;
        m_cond.notify_all();


        if(m_thread.joinable())
        {
            std::cout << "thread can join" << std::endl;
            m_thread.join();
        }
    }


    void append(std::string str);


    void stop()
    {
        m_bNeedRun = false;
        m_cond.notify_all();
    }

private:
    void backWork();//线程入口函数

    typedef std::vector<std::string> Buffer;
    typedef std::vector<std::unique_ptr<Buffer>> BufferPool;
    typedef BufferPool::value_type BufferPtr;
//    typedef std::unique_ptr<Buffer> BufferPtr;

    const int m_nFlushInterval;
    std::atomic_bool m_bNeedRun;

    std::thread m_thread;
    std::mutex m_mutex;//保护所有buffer相关对象
    std::condition_variable m_cond;
//    ThreadGuard m_thGuard;

    const int m_nBufferSize;
    BufferPtr m_pCurrentBuffer;
    BufferPtr m_pNextBuffer;
    BufferPool m_BufferPool;
};

#endif // THREAD_TEST_H
